<template>
  <view>
    <view class="fixed bg-f8ff w-100 h-100 top0 left0 ov-hd-y">
      <itemTitle :key="details.id" :item="details"></itemTitle>
      <view class="w-100 px-2-6">
        <view class="w-100 py-3">
          <view class="w-100 h1 bg-ccc"></view>
        </view>

        <SelectTime type="click" :item="address"></SelectTime>
      </view>

      <view class="w-100 px-5 pt-3">
        <view class="font28 font500 t-20 pb-2">商品详情</view>
        <view
          v-if="address.remainNumber"
          style="color: #8a8a8a; font-size: 22rpx; margin-bottom: 20rpx"
          >剩余库存：{{ address.remainNumber }}</view
        >
        <richText :key="details.id" :rich_text="details.content"></richText>

        <view class="w-100 h100"></view>
      </view>

      <view class="w-100 h340"></view>
    </view>

    <view class="w-100 fixed bottom0 pb-5 pt-2 left0 z-999 bg-f8ff show0-top">
      <view class="w-100 f-b-c pl-5 pr-2 h80">
        <view class="font28 font500">购买数量</view>
        <view class="f-b-c">
          <view class="w80 py-2 pl-4" @click="set_reduce">
            <view
              class="w40 h40 font40 font600 rounded-circle f-c-c pb-1"
              :class="number <= 1 ? 't-3' : 't-20 bg-theme'"
              >-</view
            >
          </view>
          <view class="px-3 h80 font28 font500 t-20 f-c-c">{{ number }}</view>
          <view class="w80 py-2 pr-4" @click="set_add">
            <view
              class="w40 h40 font40 font600 rounded-circle t-20 f-c-c pb-1 bg-theme"
              >+</view
            >
          </view>
        </view>
      </view>

      <view class="w-100 px-4 pt-3">
        <view class="w-100 f-b-c bg-theme_3 h100 circle120 pl-5">
          <view class="pl-1 font28 font700 t-w">
            <text class="font24 font400 mr-05">合计</text>¥{{ money }}
          </view>
          <view
            v-if="isLogin"
            class="w220 h100 f-c-c bg-theme circle120 font28 font700 t-20"
            @click="show_purchase"
            >立即购买</view
          >
          <view
            v-else
            class="w220 h100 f-c-c bg-theme circle120 font28 font700 t-20"
            @click="set_go_login"
            >去登录</view
          >
        </view>
      </view>
    </view>

    <uni-popup ref="activity_ref" class="ssss" type="center">
      <view class="w696 h596 circle54 bg-f8ff ov-hd show0">
        <view
          class="w-100 h146 f-c-c bg-theme radius-54-botton font40 t-0 font600"
        >
          活动确认
        </view>
        <view class="w-100 h450 bg-theme">
          <view class="w-100 h-100 bg-f8ff radius-54-right px-6 py-6">
            <view class="font28 t-20 font700 pb-2 f-y-c h44">{{
              address.activityName
            }}</view>
            <view class="font25 t-8 font400 mb-1 f-y-c h28"
              >{{ address.activityDate }} {{ address.weeks }}</view
            >
            <view class="font25 t-8 font400 mb-1 f-y-c h28"
              >{{ address.startTime }}-{{ address.endTime }}</view
            >
            <view class="font25 t-8 font400 mb-1 f-y-c h28">{{
              address.activityAddress
            }}</view>
            <view class="font28 t-20 font500 pt-2 f-y-c h44"
              >需支付<text class="mx-06">:</text>¥{{ details.price }}</view
            >
            <view class="w-100 h140 f-b-c pt-5">
              <view
                class="w270 h90 bg-dd font32 t-20 font600 f-c-c circle14"
                @click="set_cancel"
                >取消</view
              >
              <view
                class="w270 h90 bg-theme font32 t-20 font600 f-c-c circle14"
                @click="get_purchass()"
                >确定</view
              >
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
    <SignUp ref="signUp" />
  </view>
</template>

<script>
import SelectTime from "./components/select-time.vue";
import itemTitle from "../../ticket/components/title.vue";
import richText from "../../ticket/components/rich-text.vue";
import { activityId } from "../../../api/ticket/index.js";
import { order_submit } from "../../../api/order.js";
import weixin_pay from "../../../common/weixinPay.js";
import isLoginMxin from "../../../common/isLogin.js";
export default {
  mixins: [weixin_pay, isLoginMxin],
  components: { SelectTime, itemTitle, richText },
  data() {
    return {
      details: {},
      address: {},
      cur_id: 0,
      number: 1,
      money: 0,
    };
  },
  created() {
    // let details = uni.getStorageSync("details") || {};
    // this.get_details(details.id);
    // this.money = 0;
    // this.money = details.price.toFixed(2);
  },
  onLoad(val) {
    // this.cur_id = val.is_cur_id;
    this.initPage(val.is_cur_id);
  },
  mounted() {
    uni.$on("backPage", (e) => {
      this.initPage(e);
    });
  },
  destroyed() {
    uni.$off("backPage");
  },
  methods: {
    initPage(e) {
      this.cur_id = e;
      console.log("back", e);
      let details = uni.getStorageSync("details") || {};
      this.get_details(details.id);
      this.money = 0;
      this.money = details.price.toFixed(2);
    },
    show_purchase() {
      if (
        !this.$validateStock(
          { stock: true, remainStockNum: this.address.remainNumber },
          this.number
        )
      ) {
        return uni.showToast({
          title: "库存不足，请重新选择",
          icon: "none",
        });
      }
      if (this.address.remainNumber == 0) {
        return uni.showToast({
          title: "当前活动已满员",
          icon: "none",
        });
      }
      // this.$refs.activity_ref.open()
      // uni.setStorageSync("purchase_type",'ACTIVITY')
      this.details.number = this.number;
      (this.details.addressId = this.address.id), // 活动排班id 排班订单不能为空
        uni.setStorageSync("createdOrder", this.details);
      uni.navigateTo({
        url: "/pages/purchase/index",
      });
    },
    set_cancel() {
      this.$refs.activity_ref.close();
    },
    // 获取详情
    get_details(id) {
      activityId({ id }).then((res) => {
        if (res.code === "0") {
          this.details = res.body;
          this.money = res.body.price.toFixed(2);
          let obj = {};
          res.body?.planList?.map((item) => {
            item.weeks = this.set_week(item.weekday);
            item.activityName = res.body.contactName;
            item.activityAddress = res.body.address;
            // 获取选中的时间段
            if (item.id == this.cur_id) {
              obj = item;
            }
          });
          // 如果有选中的时间段 就使用选择的时间段 没有就默认第一个
          let plan = res.body?.planList?.find(
            (item) => item.usedNumber < item.totalNumber
          );
          this.address = obj.id ? obj : plan || {};

          console.log("obj", obj);
          console.log("address", this.address);
          if (!this.address.id) {
            this.address = res.body?.planList[0];
          }

          // 每次获取到到新时间 存到缓存 点击选择时间段到时候使用
          uni.setStorageSync("select_time", res.body?.planList || []);
        }
      });
    },
    set_reduce() {
      if (this.number <= 1) {
        return;
      } else {
        this.number--;
      }
      this.total();
    },
    set_add() {
      if (this.number == this.address.remainNumber) {
        return uni.showToast({
          title: "当前最多可报名" + this.number + "次",
          icon: "none",
        });
      }
      this.number++;
      this.total();
    },
    total() {
      this.money = (this.number * this.details.price).toFixed(2);
    },
    set_week(val) {
      let text = "";
      switch (val) {
        // MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY
        case "MONDAY":
          text = "星期一";
          break;
        case "TUESDAY":
          text = "星期二";
          break;
        case "WEDNESDAY":
          text = "星期三";
          break;
        case "THURSDAY":
          text = "星期四";
          break;
        case "FRIDAY":
          text = "星期五";
          break;
        case "SATURDAY":
          text = "星期六";
          break;
        case "SUNDAY":
          text = "星期日";
          break;
      }
      return text;
    },
    // 设置订单信息
    set_goods_list(array) {
      const list = [];
      let totalFee = 0;
      let totalNum = 0;
      array?.map((item) => {
        list.push({});
        totalFee += parseFloat((item.number * item.price).toFixed(2));
        totalNum += item.number;
      });
      return { list, totalFee, totalNum };
    },
    async get_purchass() {
      const userInfo = uni.getStorageSync("userInfo") || {};
      const orgId = uni.getStorageSync("orgId") || "";

      let data = {
        orgId: orgId,
        payFee: this.details.price, // 支付金额
        memberId: userInfo.id,
        payType: "WECHAT_PAY", //payType：支付类型 WECHAT_PAY:微信支付/MEMBER_CARD:会员卡支付
        remark: "",
        subOrderList: [
          {
            addressId: "",
            couponFee: "",
            couponId: "",
            freightFee: 0, //运费
            goodsList: [
              {
                activityPlanId: this.address.id, // 活动排班id 排班订单不能为空
                date: "", //预约日期 票务订单不能为空
                lineItemType: "", //路线类型 1：材料包/2：导览服务
                goodsId: this.details.id,
                goodsName: this.details.name,
                number: 1,
                totalFee: this.details.price,
                unitFee: this.details.price,
              },
            ],
            payFee: this.details.price,
            orderType: "ACTIVITY", //food FOOD,TICKET,YEAR_CARD,MALL,MAP ,LINE
            tableNo: "", // 桌号
            totalFee: this.details.price,
            totalNum: 1,
          },
        ],
      };

      const { code, body } = await order_submit(data);
      if (code === "0") {
        let id_list = body?.orderList.map((item) => item.id);
        let pay_info = {
          orderIdList: id_list, // 订单id集合
          payFee: data.payFee, // 支付金额
          id: id_list[0], //订单id
          payStatus: body.payStatus, // 支付状态 0元
          orderId: "ACTIVITY", //
        };
        // 去提交支付
        this.get_wx_order(pay_info, "ACTIVITY");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.radius-54-botton {
  border-radius: 54rpx 54rpx 0 54rpx;
}
.radius-54-right {
  border-radius: 0 54rpx 0 0;
}
</style>
